import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liukaixin on 16/5/19.
 */
public class DiscountManager {

    public static String NO_DISCOUNT = "NO DISCOUNT";
    public static String BUY_THREE_GET_ONE_FREE = "BUY_THREE_GET_ONE_FREE";
    //所有的优惠商品链表
    private List<Discount> discountList = new ArrayList<>();
    //用户买的被优惠的商品链表
    private List<GoodsBeingDiscounted> goodsBeingDiscountedsList = new ArrayList<>();

    private static DiscountManager discountManager = new DiscountManager();

    private DiscountManager() {

    }

    public static DiscountManager getDiscountManager() {
        return discountManager;
    }

    //设置优惠商品链表
    public void setDiscountGoods(String jsonString) {
        String[] discountGoods = JSONDecoder.decodeArrayFrom(jsonString);
        for (String discountGood : discountGoods) {
            Discount discount = new Discount();
            discount.setType(JSONDecoder.decodeStringWithName(discountGood, "type"));
            discount.setDiscountItems(JSONDecoder.decodeArrayFrom(new JSONObject(discountGood).getJSONArray("barcodes").toString()));
            this.discountList.add(discount);
        }
    }

    //根据条形码获得某商品的优惠类型
    public String getDiscountType(String barcode) {
        Discount discount;
        for (Discount aDiscountList : discountList) {
            discount = aDiscountList;
            for (int j = 0; j < discount.getDiscountItems().length; j++) {
                if (discount.getDiscountItems()[j].equals(barcode)) {
                    return discount.getType();
                }
            }
        }
        return DiscountManager.NO_DISCOUNT;
    }

    //获得某商品打折后的总价
    public double NewGetTotalPriceAfterDiscountFor(String barcode, int count) {
        ProductManager productManager = ProductManager.getProductManager();
        Product product = productManager.getProductByBarcode(barcode);

        DiscountChain buyThreeFreeOneDiscount = new BuyThreeFreeOneDiscountHandler();
        buyThreeFreeOneDiscount.next(null);
        GoodsBeingDiscounted goodsBeingDiscounted = buyThreeFreeOneDiscount.getPriceAfterDiscount(product, count);

        if (goodsBeingDiscounted.getPriceAfterDiscount() != goodsBeingDiscounted.getPriceBeforeDiscount()) {
            this.goodsBeingDiscountedsList.add(goodsBeingDiscounted);
        }

        return goodsBeingDiscounted.getPriceAfterDiscount();
    }

    public List<GoodsBeingDiscounted> getGoodsBeingDiscountedsList() {
        return goodsBeingDiscountedsList;
    }
}
